package com.create404.suishoupai.utils;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.create404.suishoupai.entity.ChatRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class SendUtils {
    protected static final Logger LOG = LoggerFactory.getLogger(SendUtils.class);

    // demo App defined in resources/jpush-api.conf
    protected static final String APP_KEY = "2955f1df53ba83f2e437f41d";
    protected static final String MASTER_SECRET = "19aa2dc536795f28387cd251";



    public static PushResult testSendPush(ChatRecord record) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        final PushPayload payload = buildPushObject_android_and_ios(record);
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("获得结果" + result);
            System.out.println(result);
            return result;
        } catch (APIConnectionException e) {
            LOG.error("连接错误 ", e);
            LOG.error("发送号码为: " + payload.getSendno());
        } catch (APIRequestException e) {
            LOG.error("极光服务器回复错误 ", e);
            LOG.error("Sendno: " + payload.getSendno());
        }
        return null;
    }


    public static PushPayload buildPushObject_android_and_ios(ChatRecord record) {
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("id", record.getSenderId());
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag(record.getReceiverId()))
                .setNotification(Notification.newBuilder()
                        .setAlert(record.getContent())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle("你有一条新消息")
                                .addExtras(extras).build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .addExtra("extra_key", "extra_value").build())
                        .build())
                .build();
    }


}
